home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3891 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  78 lines

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Overload >> vs. Write Met
  5. Date: 26 Jan 1996 16:57:01 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan26115701@g7240065.bridge.bst.bls.com>
  8. References: <60125190005$71C7@lasernet.com>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: GEORGE BOUTWELL's message of Thu, 25 Jan 96 16:20:00 LOC
  11.  
  12. In article <60125190005$71C7@lasernet.com> GEORGE BOUTWELL <george_boutwell@lasernet.com> writes:
  13.  
  14. : Ok...
  15.  
  16. :   Which is 'better' OOP 'Style', and/or 'Correctness' for
  17. : Writing/Reading an Object's Data to/from Disk/Screen/Etc:
  18.  
  19. : Overloading the << and >>
  20. : -or-
  21. : writing a read method and a write method?
  22.  
  23. IMHO both.
  24.  
  25. The problem with the operators << and >> is that they are usually (friend)
  26. global functions and as such cannot be virtual.
  27.  
  28. The advantage of operator >> and << is that you read and write things
  29. from a stream in a consistent way.
  30.  
  31. Read and write have the advantage of being able to be virtual.
  32.  
  33. So the best solution is to combine them - implement operator << and >>
  34. in terms of read and write
  35.  
  36. Example - only deals with write, read is left for an exercise of the reader ;')
  37.  
  38. #include <iostream.h>
  39.  
  40. class Base
  41. {
  42.    public:
  43.      virtual ostream& write(ostream& out) const
  44.      { return out << "Base" << endl; }
  45. };
  46.  
  47. ostream& operator << (ostream& out, const Base& base)
  48. {
  49.     return base.write(out);
  50. }
  51.  
  52. class Derived : public Base
  53. {
  54.   public:
  55.      virtual ostream& write(ostream& out) const
  56.      { return out << "Derived" << endl; }
  57. };
  58.  
  59. int
  60. main(void)
  61. {
  62.     Base b;
  63.     Derived d;
  64.     Base& ref = d;
  65.  
  66.     cout << b;        // writes "Base"
  67.     cout << d;        // writes "Derived"
  68.     cout << ref;    // writes "Derived"
  69.  
  70.     return 0;
  71. }    
  72.  
  73. Regards
  74.  
  75.    -A.
  76. -- 
  77. | A.Champion                |
  78.